package myXmlRPCRemote.apk;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MyXmlRPCRemoteActivity
	extends Activity
	implements android.view.View.OnClickListener, OnSharedPreferenceChangeListener, OnItemLongClickListener {
	String _hostname;
	XMLRPCClient _client;
	HashMap<String, Object> _Layout;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                
        _client = null;
        _Layout = null;
        _ListItems = null;
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this);
        
        _hostname = prefs.getString("hostname", "10.0.2.2");
        
        loadLayout();
   	}
    
    @Override
    protected void onStop() {
		super.onStop();
		
		SharedPreferences settings = getSharedPreferences("MyXmlRPCRemote", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("hostname", _hostname);
		editor.commit();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(Menu.NONE, R.id.SettingsMenu, Menu.NONE, "Settings");
    	menu.add(Menu.NONE, R.id.LoadLayout, Menu.NONE, "Reload Layout");
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected (MenuItem item) {
    	switch (item.getItemId()) {
    		case R.id.SettingsMenu:
    			// Launch Preference activity
    			Intent i = new Intent(this, MyXmlRPCRemotePreferencesActivity.class);
   				startActivity(i);
   				_client = null;
    			break;
    		case R.id.LoadLayout:
    			_client = null;
    			loadLayout();
        		break;
    	}
    	
    	if (item.getTitle() == "Load Layout") {
    		loadLayout();
    	} else if (item.getTitle() == "Save Settings") {
    		
    	}
    	return super.onOptionsItemSelected(item);
    }

	public void onClick(View v) {
		createClient();
		
		Button CurrentButton = (Button)findViewById(v.getId());
		if (CurrentButton == null) {	// layout buttons have no ID!
			Object CommandID = v.getTag(R.id.CommandID);
			callCommand(CommandID);
		}
	}
	
	public boolean onItemLongClick(AdapterView<?> arg0, View v, int position, long id) {
		createClient();
		
		Object CommandID = ((View)v.getParent()).getTag(R.id.CommandID);
		callCommandArg(CommandID, _ListItems[position]);
		
		return true;
	}

	private void createClient() {
		if (_client == null) {
			_client = new XMLRPCClient("http://" + _hostname + ":5678/MyXmlRPCRemote.rem");
		}
	}

	private void callCommand(Object CommandID) {
		try {
			_client.call("MyXmlRPCRemote.CallCommand", CommandID);
		} catch (XMLRPCException e) {
			AlertDialog alertDialog;
			alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Error");
			alertDialog.setMessage(e.getMessage());
			alertDialog.show();
		}
	}
	
	private void callCommandArg(Object CommandID, Object Arg) {
		try {
			_client.call("MyXmlRPCRemote.CallCommandArg", CommandID, Arg);
		} catch (XMLRPCException e) {
			AlertDialog alertDialog;
			alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Error");
			alertDialog.setMessage(e.getMessage());
			alertDialog.show();
		}
	}

	private void loadLayout() {
		LinearLayout LayoutContainer = (LinearLayout)findViewById(R.id.LayoutContainer);
		LayoutContainer.removeAllViews();
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		int displayHeight = metrics.heightPixels;
		
		createClient();
	
		try {
			_Layout = (HashMap<String, Object>) _client.call("MyXmlRPCRemote.GetLayout");
			Object[] Rows = (Object[]) _Layout.get("Rows");
			
			int FullHeightUnits = (Integer) _Layout.get("Height");
			
			for(int i = 0; i < Rows.length; i++) {
				TableLayout table = new TableLayout(this);
				table.setStretchAllColumns(true);
				TableRow tableRow = new TableRow(this);
				
				HashMap<String, Object> Row = (HashMap<String, Object>) Rows[i];
				Object[] Elements = (Object[]) Row.get("Elements");
				
				for (int j = 0; j < Elements.length; j++) {
 					HashMap<String, Object> Element = (HashMap<String, Object>) Elements[j];
					
					// in case of a button
					if (Element.get("Type") == (Object) 1) {		
					    Button button = new Button(this);
					    button.setText((String)Element.get("Label"));
					    button.setTag(R.id.CommandID, Element.get("CommandID"));
					    button.setOnClickListener(this);
					    button.setMinimumHeight((displayHeight / (FullHeightUnits + 1)) * (Integer)Element.get("Height"));
					    tableRow.addView(button);
					}
					
					// in case of a List
					if (Element.get("Type") == (Object) 2) {
						Object CommandID = Element.get("CommandID");
						Object[] ListContent = (Object[])_client.call("MyXmlRPCRemote.GetList", CommandID);
						
						// copy the array - ugly yes...
						String[] ListItems = new String[ListContent.length];
						for (int k = 0; k < ListContent.length; k++) {
							ListItems[k] = (String) ListContent[k];
						}
						
					    ListView list = new ListView(this);
					    list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ListItems));
					    list.setTag(R.id.CommandID, Element.get("CommandID"));
					    list.setOnItemLongClickListener(this);
					    list.setMinimumHeight((displayHeight / (FullHeightUnits + 1)) * (Integer)Element.get("Height"));
					    tableRow.addView(list);
					}
				}
				
		        table.addView(tableRow,new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		        LayoutContainer.addView(table);
			}
			
		} catch (XMLRPCException e) {
			AlertDialog alertDialog;
			alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Error");
			alertDialog.setMessage(e.getMessage());
			alertDialog.show();
		}
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("hostname")) {
            _hostname = sharedPreferences.getString("hostname", "10.0.2.2");
            _client = null;
            loadLayout();
        }	
	}
}